package com.leff.cards.request;

import com.leff.cards.CloudMessenger;
import com.leff.cards.Dictionary;
import com.leff.cards.StoreWrapper;
import com.leff.cards.entity.Group;
import com.leff.cards.entity.Invitation;
import com.leff.cards.entity.User;

public class InviteUser extends Request {

	public InviteUser(Dictionary dict) {
		super(dict);
	}
	
	public RequestResult doInvite() {
		
		RequestResult result = this.verifyRequiredParameters(Parameter.GROUP_ID, Parameter.FB_ID);
		if(!result.isSuccessful()) {
			return result;
		}
		
		long groupId = Long.valueOf(mDictionary.get(Parameter.GROUP_ID).toString());
		Group G = StoreWrapper.getGroupById(groupId);
		if(G == null) {
			result.setErrorResult("No group found with ID " + groupId);
			return result;
		}
		
		String fbidStr = (String)mDictionary.get(Parameter.FB_ID);
		String[] allIdStrs = fbidStr.split(",");
		
		Dictionary results = new Dictionary();
		
		int existed = 0;
		int invited = 0;
		
		for(String idStr : allIdStrs) {
			
			long fbid = Long.parseLong(idStr);
			
			if(StoreWrapper.inivitationExists(groupId, fbid)) {
				results.put(idStr, "Invitation Already Exists");
				existed++;
				continue;
			}
			
			Invitation I = new Invitation(groupId, fbid);
			StoreWrapper.store(I);

			results.put(idStr, "Invited");
			invited++;
			
			// If user is already a player, send them a PN
			User U = StoreWrapper.getUserByFbId(fbid);
			if(U != null) {
				CloudMessenger.sendInviteMessage(G, U);
			}
		}
		
		results.put("invited", invited);
		results.put("existed", existed);
		
		result.res = results;
		
		return result;
	}
}
